package com.linqi.freebie.http.ktorClientCio.interceptor

import io.github.aakira.napier.Napier
import io.ktor.client.request.HttpRequestBuilder
import io.ktor.client.statement.HttpResponse
import io.ktor.http.Url

class BaseUrlInterceptor(
    private val baseUrlProvider: () -> String
) : HttpInterceptor {

    override suspend fun onRequest(builder: HttpRequestBuilder) {
        try {
            val currentHost = builder.url.host
            val originalFullUrl = builder.url.buildString()

            // 如果当前URL已经有合法的host，并且不是"localhost"这种默认值
            if (currentHost.isNotBlank() && currentHost != "localhost") {
                Napier.d("BaseUrlInterceptor -> 保持原始URL: $originalFullUrl", tag = "HttpLog")
                return
            }

            val baseUrl = Url(baseUrlProvider())

            // 替换协议、host、port，保留 path 和 query
            builder.url {
                protocol = baseUrl.protocol
                host = baseUrl.host
                port = baseUrl.port
            }

            Napier.d("BaseUrlInterceptor -> 应用BaseUrl: $baseUrl -> ${builder.url}", tag = "HttpLog")
        } catch (e: Exception) {
            Napier.e("BaseUrlInterceptor onRequest异常: ${e.message}", e, tag = "HttpLog")
        }
    }

    override suspend fun onResponse(response: HttpResponse) {
        // 不处理响应
    }
}
